package cn.minhx.domain.trade.service.lock.filter;

import cn.minhx.domain.activity.model.valobj.ActivityStatusEnumVO;
import cn.minhx.domain.trade.adapter.repostitory.ITradeRepository;
import cn.minhx.domain.trade.moedel.entity.GroupBuyActivityEntity;
import cn.minhx.domain.trade.moedel.entity.TradeLockRuleCommandEntity;
import cn.minhx.domain.trade.moedel.entity.TradeLockRuleFilterBackEntity;
import cn.minhx.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import cn.minhx.types.design.link.multi.handler.ILogicHandler;
import cn.minhx.types.enums.ResponseCode;
import cn.minhx.types.exception.AppException;
import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 活动有效规则过滤器
 *
 * @author min
 */
@Slf4j
@Service
public class ActivityUsabilityRuleFilter
		implements
			ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {

	@Resource
	private ITradeRepository repository;

	@Override
	public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter,
			TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
		log.info("交易规则过滤-活动的可用性校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());
		// 查询拼团活动
		GroupBuyActivityEntity groupBuyActivity = repository
				.queryGroupBuyActivityEntityByActivityId(requestParameter.getActivityId());
		// 校验；活动状态 - 可以抛业务异常code，或者把code写入到动态上下文dynamicContext中，最后获取。
		if (!ActivityStatusEnumVO.EFFECTIVE.equals(groupBuyActivity.getStatus())) {
			log.info("活动的可用性校验，非生效状态 activityId:{}", requestParameter.getActivityId());
			throw new AppException(ResponseCode.E0101);
		}
		// 校验；活动时间
		LocalDateTime currentTime = LocalDateTime.now();
		if (currentTime.isBefore(groupBuyActivity.getStartTime())
				|| currentTime.isAfter(groupBuyActivity.getEndTime())) {
			log.info("活动的可用性校验，非可参与时间范围 activityId:{}", requestParameter.getActivityId());
			throw new AppException(ResponseCode.E0102);
		}
		// 写入动态上下文
		dynamicContext.setGroupBuyActivity(groupBuyActivity);
		// 走到下一个责任链节点
		return next(requestParameter, dynamicContext);
	}
}
